#include "grayBMPLoad.h"

BMPfile::BMPfile(const std::string& str)
{
  iFile.open(str,std::ios::binary);
  if(!iFile.is_open())
    throw std::logic_error("无法打开文件");
  char c;
  iFile.seekg(0x02,std::ios::beg);
  iFile.read((char*)&imageSize,sizeof(int32_t));
  iFile.seekg(0x0A,std::ios::beg);
  iFile.read((char*)&imageDataOffset,sizeof(int16_t));
  iFile.seekg(0x12,std::ios::beg);
  iFile.read((char*)&imgInfo.width,sizeof(int32_t));
  iFile.seekg(0x16,std::ios::beg);
  iFile.read((char*)&imgInfo.height,sizeof(int32_t));
  int16_t pixelBit;
  iFile.seekg(0x1C,std::ios::beg);
  iFile.read((char*)&pixelBit,sizeof(int16_t));
  switch(pixelBit)
  {
    case 8:
      imgInfo.channel=1;
      break;
    case 24:
      imgInfo.channel=3;
      break;
    default:
      throw std::logic_error("不支持的图像格式");
      break;
  }
  imageSize=imgInfo.width*imgInfo.height*imgInfo.channel;
  imageData=new char[imageSize];
  iFile.seekg(imageDataOffset,std::ios::beg);
  iFile.read(imageData,imageSize);
}

BMPfile::~BMPfile()
{
  if(iFile.is_open())
    iFile.close();
  if(imageData!=nullptr)
    delete [] imageData;
}

char* BMPfile::GetImageData()
{
 return imageData;
}

ImageInfo BMPfile::GetImageInfo()
{
  return imgInfo;
}
